import express from 'express';
import {
    apolloServer as graphql
} from 'apollo-server';
import cmd from './cmd';
import log from './log';
import cfg from '../etc';

const app = express();
app.disable('x-powered-by');
const dev = app.get('env') === 'development';

// 日志记录
if (!dev) {
    app.use(require('log4js').connectLogger(
        log, {level: 'auto'}
    ));
} else {
    app.use(require('morgan')('dev'));
}

// 静态文件
app.use(express.static(cfg.root));

// 数据服务路径
let data = cfg.data || 'graphql';
if (data[0] !== '/') {
    data = `/${data}`;
}

// 状态测试
app.get(`${data}/status`, (req, res) => {
    const t = require('moment')(app.locals.server_started_at);
    res.send(`running ${t.fromNow(true)} since ${t.format('YYYY-MM-DD hh:mm:ss')}`);
});

// 数据服务
import schema from './_';
import {addErrorLoggingToSchema} from 'graphql-tools';
const logger = {log: (e) => log.error(e.stack)};
addErrorLoggingToSchema(schema, logger);
app.use(data, graphql({
    graphiql: dev,
    pretty: dev,
    context: {},
    schema
}));

// 错误处理
if (dev) {
    app.use(require('errorhandler')());
}

// 启动服务
const server = app.listen(cmd.port || cfg.port, cfg.ip, (err) => {
    if (err) {
        log.error(err);
    } else {
        app.locals.server_started_at = new Date();
        log.info('started at', server.address().port);
    }
});
